<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

namespace app\services\order;


use app\dao\order\OtherOrderDao;
use app\jobs\store\StoreFinanceJob;
use app\jobs\user\UserBelongStoreJob;
use app\services\BaseServices;
use app\services\pay\OrderPayServices;
use app\services\pay\PayServices;
use app\services\statistic\TradeStatisticServices;
use app\services\user\member\MemberShipServices;
use app\services\user\UserBillServices;
use app\services\user\UserServices;
use crmeb\services\AliPayService;
use crmeb\services\wechat\Payment;
use crmeb\traits\ServicesTrait;
use think\exception\ValidateException;
use app\jobs\user\MicroPayOrderJob;

/**
 * Class OtherOrderServices
 * @package app\services\order
 * @mixin OtherOrderDao
 */
class OtherOrderServices extends BaseServices
{

    use ServicesTrait;

    /**
     * 订单类型
     * @var string[]
     */
    protected $type = [
        0 => '免费领取',
        1 => '购买会员卡',
        2 => '卡密激活',
        3 => '收银订单',
        4 => '赠送'
    ];

    /**
     * 初始化，获得dao层句柄
     * OtherOrderServices constructor.
     * @param OtherOrderDao $dao
     */
    public function __construct(OtherOrderDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * @param int $storeId
     * @return int
     */
    public function getvipOrderCount(int $storeId)
    {
        return $this->dao->count(['store_id' => $storeId, 'paid' => 1, 'type' => [0, 1, 2, 4]]);
    }

	/**
	 * 生成会员购买订单数据
	 * @param array $data
	 * @param int $type
	 * @param string $changeType
	 * @return \crmeb\basic\BaseModel|\think\Model
	 */
    public function addOtherOrderData(array $data, int $type = 1, string $changeType = 'create_member_order', int $is_integral=0)
    {
        if (!$data) throw new ValidateException('数据不能为空');
        $add = [
            'uid' => $data['uid'],
            'store_id' => $data['store_id'] ?? 0,
            'staff_id' => $data['staff_id'] ?? 0,
            'type' => $data['type'] ?? 1,
            'order_id' => $data['order_id'],
            'channel_type' => $data['channel_type'],
            'pay_type' => $data['pay_type'] ?? 0,
            'member_type' => $data['member_type'] ?? 0,
            'member_price' => $data['member_price'] ?? 0.00,
            'pay_price' => $data['pay_price'] ?? 0.00,
            'code' => $data['member_code'] ?? '',
            'vip_day' => $data['vip_day'] ?? 0,
            'is_permanent' => $data['is_permanent'] ?? 0,
            'is_free' => $data['is_free'] ?? 0,
            'overdue_time' => $data['overdue_time'] ?? 0,
            'status' => 0,
            'paid' => $data['paid'] ?? 0,
            'pay_time' => $data['pay_time'] ?? 0,
            'money' => $data['money'] ?? 0,
            'add_time' => time(),
        ];
		$res = $this->dao->save($add);
		if (!$res) {
			throw new ValidateException('订单创建失败');
		}
		/** @var OtherOrderStatusServices $statusService */
		$statusService = app()->make(OtherOrderStatusServices::class);
		$statusService->save([
			'oid' => $res['id'],
			'change_type' => $changeType,
			'change_message' => '订单生成',
			'change_time' => time(),
			'shop_type' => $type,
		]);
		
		
		if($is_integral == 1) {
            try {
                //减积分
                $userService = app()->make(UserServices::class);
                $userInfo = $userService->getUserInfo($data['uid']);
                $userInfo = $userInfo->toArray();
                $this->deductIntegral($userInfo, $data['member_price'], (int)$userInfo['uid'], $data['order_id']);
            }catch (\Throwable $e){
                throw new ValidateException($e->getMessage());
            }
        }
		
		
        return $res;
    }


    public function deductIntegral(array $userInfo, $priceIntegral, int $uid, string $orderId)
    {
        $res2 = true;
        if ($userInfo['integral'] > 0) {
            /** @var UserServices $userServices */
            $userServices = app()->make(UserServices::class);
            if ($userInfo['integral'] >= $priceIntegral) {
                $integral = bcsub((string)$userInfo['integral'], (string)$priceIntegral);
            } else {
                throw new ValidateException('积分不足抵扣');
                $integral = 0;
            }
            $res2 = $userServices->update($uid, ['integral' => $integral]);
            /** @var UserBillServices $userBillServices */
            $userBillServices = app()->make(UserBillServices::class);
            $res3 = $userBillServices->income('storeIntegral_use_integral_vip', $uid, (int)$priceIntegral, (int)$integral, $orderId);
            $res2 = $res2 && false != $res3;
        }else{
            throw new ValidateException('积分不足');
        }

        if (!$res2) {
            throw new ValidateException('使用积分抵扣失败!');
        }
    }




    /**
     * 能否领取免费
     * @param int $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function isCanGetFree(int $uid)
    {
        /** @var UserServices $userService */
        $userService = app()->make(UserServices::class);
        /** @var MemberShipServices $memberShipService */
        $memberShipService = app()->make(MemberShipServices::class);
        /** @var TradeStatisticServices $tradeService */
        $tradeService = app()->make(TradeStatisticServices::class);
        /** @var StoreOrderEconomizeServices $economizeService */
        $economizeService = app()->make(StoreOrderEconomizeServices::class);
        $freeDay = $memberShipService->getVipDay(['type' => "free"]);
        $freeConfig = array();
        $freeConfig['price'] = 0;
        $freeConfig['pre_price'] = 0;
        $freeConfig['title'] = "免费会员";
        $freeConfig['type'] = "free";
        $freeConfig['vip_day'] = $freeDay ? $freeDay : 0;
        $userInfo = $userService->get($uid);
        if ($freeConfig) {
            $freeConfig['is_record'] = 0;
            $record = $this->dao->getOneByWhere(['uid' => $uid, 'is_free' => 1]);
            if ($record) {
                $freeConfig['is_record'] = 1;
            }
        }
        $registerTime = $tradeService->TimeConvert(['start_time' => date('Y-m-d H:i:s', $userInfo['add_time']), 'end_time' => date('Y-m-d H:i:s', time())]);
        $userInfo['register_days'] = $registerTime['days'];
        $userInfo['economize_money'] = $economizeService->sumEconomizeMoney($uid);
        $userInfo['shop_name'] = sys_config('site_name');
        $freeConfig['user_info'] = $userInfo;
        return $freeConfig;
    }


    /**
     * 查询会员卡订单数据
     * @param array $where
     * @param string $field
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOne(array $where, string $field = '*')
    {
        return $this->dao->getOne($where, $field);
    }

	/**
	 * 创建订单
	 * @param int $uid
	 * @param int $memberId
	 * @param string $payPrice
	 * @param string $channelType
	 * @param string $payType
	 * @param $type
	 * @param int $store_id
	 * @param int $staff_id
	 * @return \crmeb\basic\BaseModel|\think\Model
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
    public function createOrder(int $uid, int $memberId, string $payPrice = '0', string $channelType = 'h5', string $payType = 'weixin', $type = 1, int $store_id = 0, int $staff_id = 0, int $is_integral = 2)
    {
        /** @var StoreOrderCreateServices $storeOrderCreateService */
        $storeOrderCreateService = app()->make(StoreOrderCreateServices::class);
        $orderInfo = [
            'uid' => $uid,
            'order_id' => $storeOrderCreateService->getNewOrderId('hy'),
            'pay_type' => $payType,
            'channel_type' => $channelType,
            'member_code' => "",
            'store_id' => $store_id,
            'staff_id' => $staff_id
        ];
        if ($type != 3) { //区别 0：免费领取会员 1：购买会员  2：卡密领取会员  3：线下付款
            [$memberPrice, $isFree, $isPermanent, $overdueTime, $memberInfo] = $this->checkPayMemberType($uid, $memberId, $is_integral);
            $orderInfo['member_price'] = $memberPrice;
			$orderInfo['pay_price'] = $memberInfo['pre_price'];
            $orderInfo['money'] = $memberPrice;
            $orderInfo['vip_day'] = $memberInfo['vip_day'];
            $orderInfo['member_type'] = $memberInfo['id'];
            $orderInfo['overdue_time'] = $overdueTime;
            $orderInfo['is_permanent'] = $isPermanent;
            $orderInfo['is_free'] = $isFree;
            $orderInfo['type'] = $type;
            $changeType = "create_member_order";
        } else {
            $orderInfo['type'] = $type;
            $orderInfo['member_code'] = "";
            $changeType = "create_offline_scan_order";
            $orderInfo['money'] = $payPrice;
			$orderInfo['pay_price'] = $payPrice;
        }
        return $this->addOtherOrderData($orderInfo, $type, $changeType, $is_integral);
    }

    /**
     *
     * @param int $uid
     * @param $price
     * @param $merberId
     * @param $type
     * @param $from
     * @param array $staffinfo
     * @param string $authCode 扫码code
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function payMember(int $uid, int $memberId, float $price, int $payType, string $from, array $staffinfo = [], string $authCode = '')
    {
        /** @var UserServices $userServices */
        $userServices = app()->make(UserServices::class);
        $user = $userServices->getUserInfo($uid);
        if (!$user) {
            throw new ValidateException('用户数据不存在');
        }
		if (!$staffinfo) {
			throw new ValidateException('请稍后重试');
		}
		/** @var StoreOrderCreateServices $storeOrderCreateService */
		$storeOrderCreateService = app()->make(StoreOrderCreateServices::class);
		$orderInfo = [
			'uid' => $uid,
			'order_id' => $storeOrderCreateService->getNewOrderId('hy'),
			'channel_type' => $user['user_type'],
			'member_code' => "",
			'store_id' => $staffinfo['store_id'],
			'staff_id' => $staffinfo['id']
		];
		[$memberPrice, $isFree, $isPermanent, $overdueTime, $memberInfo] = $this->checkPayMemberType($uid, $memberId);
		$type = $memberInfo['type'] == 'free' ? 0 : 1;
		$orderInfo['member_price'] = $memberPrice;
		$orderInfo['pay_price'] = $memberInfo['pre_price'];
		$orderInfo['money'] = $memberPrice;
		$orderInfo['vip_day'] = $memberInfo['vip_day'];
		$orderInfo['member_type'] = $memberInfo['id'];
		$orderInfo['overdue_time'] = $overdueTime;
		$orderInfo['is_permanent'] = $isPermanent;
		$orderInfo['is_free'] = $isFree;
		$orderInfo['type'] = $type;
		$changeType = "create_member_order";
        switch ((int)$payType) {
            case 2://门店充值-用户扫码付款
            case 3://门店充值-付款码付款
                //自动判定支付方式
                if ($authCode) {
                    $orderInfo['auth_code'] = $authCode;
                    if (Payment::isWechatAuthCode($authCode)) {
                        $orderInfo['pay_type'] = PayServices::WEIXIN_PAY;
                    } else if (AliPayService::isAliPayAuthCode($authCode)) {
                        $orderInfo['pay_type'] = PayServices::ALIAPY_PAY;
                    } else {
                        throw new ValidateException('付款二维码错误');
                    }
                } else {
                    $orderInfo['pay_type'] = $from;
                }
                $memberOrder = $this->addOtherOrderData($orderInfo, $type, $changeType);
                $memberOrder = $memberOrder->toArray();

                try {
                    /** @var OrderPayServices $payServices */
                    $payServices = app()->make(OrderPayServices::class);
                    $order_info = $payServices->otherRecharge($memberOrder,$memberOrder['pay_type'], $authCode);
                    if ($payType == 3) {
                        if ($order_info['paid'] === 1) {
                            //修改支付状态
                            $this->paySuccess($memberOrder, $memberOrder['pay_type'], ['trade_no' => $order_info['payInfo']['transaction_id'] ?? '']);
                            return [
                                'msg' => $order_info['message'],
                                'status' => 'SUCCESS',
                                'type' => $from,
                                'payInfo' => [],
                                'data' => [
                                    'jsConfig' => [],
                                    'order_id' => $memberOrder['order_id']
                                ]
                            ];
                        } else {
                            //发起支付但是还没有支付，需要在5秒后查询支付状态
                            if ($memberOrder['pay_type'] === PayServices::WEIXIN_PAY) {
                                if (isset($order_info['payInfo']['err_code']) && in_array($order_info['payInfo']['err_code'], ['AUTH_CODE_INVALID', 'NOTENOUGH'])) {
                                    return ['status' => 'ERROR', 'msg' => '支付失败', 'payInfo' => $order_info];
                                }
                                $secs = 5;
                                if (isset($order_info['payInfo']['err_code']) && $order_info['payInfo']['err_code'] === 'USERPAYING') {
                                    $secs = 10;
                                }
                                MicroPayOrderJob::dispatchSece($secs, [$memberOrder['order_id'],2]);
                            }
                            return [
                                'msg' => $order_info['message'] ?? '等待支付中',
                                'status' => 'PAY_ING',
                                'type' => $from,
                                'payInfo' => $order_info,
                                'data' => [
                                    'jsConfig' => [],
                                    'order_id' => $memberOrder['order_id']
                                ]
                            ];
                        }
                    }
                } catch (\Exception $e) {
                    \think\facade\Log::error('充值失败，原因：' . $e->getMessage());
                    throw new ValidateException('充值失败：' . $e->getMessage());
                }
                return ['msg' => '', 'status' => 'PAY', 'type' => $from, 'data' => ['jsConfig' => $order_info, 'order_id' => $memberOrder['order_id']]];
                break;
            case 4: //现金支付
                $orderInfo['pay_type'] = PayServices::CASH_PAY;
                $memberOrder = $this->addOtherOrderData($orderInfo, $type, $changeType);
                if (!$memberOrder) {
                    throw new ValidateException('订单生成失败!');
                }
                $memberOrder = $memberOrder->toArray();
                try {
                    //修改支付状态
                    $this->paySuccess($memberOrder,$memberOrder['pay_type']);
                } catch (\Exception $e) {
                    throw new ValidateException($e->getMessage());
                }
                return [
                    'msg' => '',
                    'status' => 'SUCCESS',
                    'type' => $from,
                    'payInfo' => [],
                    'data' => [
                        'jsConfig' => [],
                        'order_id' => $memberOrder['order_id']
                    ]
                ];
            break;
            default:
                throw new ValidateException('缺少参数');
                break;
        }
    }
    /**
     * 免费卡领取支付
     * @param $orderInfo
     * @return bool
     */
    public function zeroYuanPayment($orderInfo)
    {
        if ($orderInfo['paid']) {
            throw new ValidateException('该订单已支付!');
        }
        /** @var MemberShipServices $memberShipServices */
        $memberShipServices = app()->make(MemberShipServices::class);
        $member_type = $memberShipServices->value(['id' => $orderInfo['member_type']], 'type');
        if ($member_type != 'free') {
            throw new ValidateException('支付失败!');
        }
        $res = $this->paySuccess($orderInfo, 'yue');//余额支付成功
        return $res;

    }

    /**
     * 会员卡支付成功
     * @param array $orderInfo
     * @param string $paytype
     * @return bool
     */
    public function paySuccess(array $orderInfo, string $paytype = PayServices::WEIXIN_PAY, array $other = [])
    {
        /** @var OtherOrderStatusServices $statusService */
        $statusService = app()->make(OtherOrderStatusServices::class);
        /** @var UserServices $userServices */
        $userServices = app()->make(UserServices::class);
        /** @var MemberShipServices $memberShipServices */
        $memberShipServices = app()->make(MemberShipServices::class);
        $orderInfo['member_type'] = $memberShipServices->value(['id' => $orderInfo['member_type']], 'type');

        switch ($orderInfo['type']) {
            case 0 :
            case 1:
            case 2 :
                $res1 = $userServices->setMemberOverdueTime($orderInfo['vip_day'], $orderInfo['uid'], 1, $orderInfo['member_type']);
                break;
            case 3:
                $res1 = true;
                break;
        }
		$update = [];
        if (isset($other['trade_no'])) {
			$update['trade_no'] = $other['trade_no'];
        }
		$update['paid'] = 1;
		$update['pay_type'] = $paytype;
		$update['pay_time'] = time();
        $res2 = $this->dao->update($orderInfo['id'], $update);
        $res3 = $statusService->save([
            'oid' => $orderInfo['id'],
            'change_type' => 'pay_success',
            'change_message' => '用户付款成功',
            'shop_type' => $orderInfo['type'],
            'change_time' => time()
        ]);
        if ($orderInfo['store_id'] > 0) {
            $orderInfo['pay_type'] = $paytype;
            $orderInfo['pay_time'] = time();
			//门店购买svip：记录流水账单
			StoreFinanceJob::dispatch([$orderInfo, 3]);
			//记录用户归属门店
			UserBelongStoreJob::dispatch([$orderInfo['uid'], $orderInfo['store_id'], 'svip']);
        }
	    /** @var UserServices $userServices */
	    $userServices = app()->make(UserServices::class);
	    $userInfo = $userServices->get((int)$orderInfo['uid']);
	    $order_integral = 0;
	    $order_give_integral = sys_config('order_give_integral');
	    $order_integral = bcmul((string)$order_give_integral, (string)($order_integral ? $order_integral : $orderInfo['pay_price']), 0);
	    $balance = $userInfo['integral'];

	    $balance = bcadd((string)$balance, (string)$order_integral);
	    /** @var UserBillServices $userBillServices */
	    $userBillServices = app()->make(UserBillServices::class);
	    $res3 = false != $userBillServices->income('level_give_integral', $orderInfo['uid'], (int)$order_integral, (int)$balance, $orderInfo['id']);
	    $give_integral = $order_integral;

	    if ($give_integral > 0) {
		    $integral = $userInfo['integral'] + $give_integral;
		    $userInfo->integral = $integral;
		    $res1 = false != $userInfo->save();
		    $res = $res1 && $res2 && $res3;
		    //发送消息
		    event('notice.notice', [['order' => $orderInfo, 'storeTitle' => '积分奖励', 'give_integral' => $give_integral, 'integral' => $integral], 'integral_accout']);
	    }        //支付成功后发送消息
        event('user.vipPay', [$orderInfo]);
        $res = $res1 && $res2 && $res3;
        return false !== $res;
    }

    /**
     * 修改
     * @param array $where
     * @param array $data
     * @return mixed
     */
    public function update(array $where, array $data)
    {
        return $this->dao->update($where, $data);
    }

	/**
	 * 购买会员卡数据校验
	 * @param int $uid
	 * @param int $memberId
	 * @param string $payPrice
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
    public function checkPayMemberType(int $uid, int $memberId, int $is_integral)
    {
		/** @var MemberShipServices $memberShipService */
		$memberShipService = app()->make(MemberShipServices::class);
		$memberInfo = $memberShipService->getMemberInfo($memberId);
        /** @var UserServices $userService */
        $userService = app()->make(UserServices::class);
        $userInfo = $userService->get($uid);
        if ($userInfo['is_money_level'] > 0 && $userInfo['is_ever_level'] > 0) throw new ValidateException('您已是永久会员无需再购买!');

        $memberTypes = $memberInfo['type'] ?? '';
        if($is_integral == 1){
            $price = $memberInfo['integral_price'];
        }else{
            $price = $memberInfo['pre_price'];
        }

        if ($memberTypes == 'free' && $memberInfo['vip_day'] <= 0) throw new ValidateException('网络错误!');
        if ($userInfo['overdue_time'] > time()) {
            $time = $userInfo['overdue_time'];
        } else {
            $time = time();
        }
        switch ($memberTypes) {
            case "free"://免费会员
                $isCanGetFree = $this->isCanGetFree($uid);
                if ($isCanGetFree['is_record'] == 1) throw new ValidateException('您已经领取过免费会员!');
                $memberPrice = 0.00; //会员卡价格
                $isFree = 1;//代表免费
                $isPermanent = 0;//代表非永久
                $overdueTime = bcadd(bcmul(abs($memberInfo['vip_day']), "86400", 0), $time, 0);
                break;
            case "ever":
                $memberPrice = $price;
                $isFree = 0;
                $isPermanent = 1;
                $overdueTime = -1;
                break;
            default:
                $memberPrice = $price;
                $isFree = 0;
                $isPermanent = 0;
                $overdueTime =$memberShipService->getOverdueTime($uid, $memberId, $userInfo, $memberInfo);
                break;
        }
        return [$memberPrice, $isFree, $isPermanent, $overdueTime, $memberInfo];
    }

    /**
     * 根据查询用户购买会员金额
     * @param array $where
     * @return mixed
     */
    public function getMemberMoneyByWhere(array $where, string $sumField, string $selectType, string $group = "")
    {
        switch ($selectType) {
            case "sum" :
                return $this->dao->getWhereSumField($where, $sumField);
            case "group" :
                return $this->dao->getGroupField($where, $sumField, $group);
        }
    }

    /**
     * 线下收银列表
     * @param array $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getScanOrderList(array $where)
    {
        $where['type'] = 3;
        $where['paid'] = 1;
        [$page, $limit] = $this->getPageValue();
        if ($where['add_time']) {
            [$startTime, $endTime] = explode('-', $where['add_time']);
            if ($startTime || $endTime) {
                $startTime = strtotime($startTime);
                $endTime = strtotime($endTime . ' 23:59:59');
                $where['add_time'] = [$startTime, $endTime];
            }
        }
        if ($where['name']) {
            /** @var UserServices $userService */
            $userService = app()->make(UserServices::class);
            $userInfo = $userService->getUserInfoList(['nickname' => $where['name']], "uid");
            if ($userInfo) $where['uid'] = array_column($userInfo, 'uid');
        }
        $list = $this->dao->getScanOrderList($where, $page, $limit);
        /** @var UserServices $userService */
        $userService = app()->make(UserServices::class);
        if ($list) {
            $userInfos = $userService->getColumn([['uid', 'IN', array_unique(array_column($list, 'uid'))]], 'uid,phone,nickname', 'uid');
            foreach ($list as &$v) {
                $v['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
                $v['pay_time'] = $v['pay_time'] ? date('Y-m-d H:i:s', $v['pay_time']) : '';
                $v['phone'] = $userInfos[$v['uid']]['phone'] ?? '';
                $v['nickname'] = $userInfos[$v['uid']]['nickname'] ?? '';
                switch ($v['pay_type']) {
                    case "yue" :
                        $v['pay_type'] = "余额";
                        break;
                    case "weixin" :
                        $v['pay_type'] = "微信";
                        break;
                    case "alipay" :
                        $v['pay_type'] = "支付宝";
                        break;
					case "offline" :
						$v['pay_type'] = "线下支付";
						break;
					case "cash" :
						$v['pay_type'] = "现金支付";
						break;
                }
                $v['true_price'] = bcsub($v['money'], $v['pay_price'], 2);
            }
        }
        $count = $this->dao->count($where);
        return compact('list', 'count');
    }

    /**
     * 获取会员记录
     * @param array $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getMemberRecord(array $where, int $limit = 0)
    {
        $where['type'] = [0, 1, 2, 4];
        if (isset($where['add_time']) && $where['add_time']) {
            $where['time'] = $where['add_time'];
            unset($where['add_time']);
        }
        if ($limit) {
            [$page] = $this->getPageValue();
        } else {
            [$page, $limit] = $this->getPageValue();
        }
        $list = $this->dao->getMemberRecord($where, '*', ['user', 'staff'], $page, $limit);
        if ($list) {
            /** @var MemberShipServices $memberShipService */
            $memberShipService = app()->make(MemberShipServices::class);
            $shipInfo = $memberShipService->getColumn([], 'title,type', 'id');
            foreach ($list as &$v) {
                $v['overdue_time'] = $v['member_type'] == 'ever' || ($shipInfo[$v['member_type']]['type'] ?? '') == 'ever' ? '永久' : ($v['overdue_time'] ? date('Y-m-d H:i:s', $v['overdue_time']) : '');
				$v['vip_day'] = $v['member_type'] == 'ever' || ($shipInfo[$v['member_type']]['type'] ?? '') == 'ever' ? '永久' : $v['vip_day'];
                $v['member_type'] = $v['member_type'] ? ($shipInfo[$v['member_type']]['title'] ?? '') : ($this->type[$v['type']] ?? '其他');
                $v['pay_time'] = $v['pay_time'] ? date('Y-m-d H:i:s', $v['pay_time']) : '';
                $v['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
                switch ($v['pay_type']) {
                    case "yue" :
                        $v['pay_type'] = "余额";
                        break;
                    case "weixin" :
                        $v['pay_type'] = "微信";
                        break;
                    case "alipay" :
                        $v['pay_type'] = "支付宝";
                        break;
                    case "admin" :
                        $v['pay_type'] = "后台赠送";
                        break;
					case "offline" :
						$v['pay_type'] = "线下支付";
						break;
					case "cash" :
						$v['pay_type'] = "现金支付";
						break;
                }
                if ($v['type'] == 0) $v['pay_type'] = "免费领取";
                if ($v['type'] == 2) {
                    $v['pay_type'] = "卡密领取";
                    $v['member_type'] = "卡密激活";
                }
                if ($v['type'] == 1 && $v['is_free'] == 1) $v['pay_type'] = "免费领取";
                $v['user']['overdue_time'] = isset($v['user']['overdue_time']) ? (date('Y-m-d', $v['user']['overdue_time']) == "1970-01-01" ? "" : date('Y-m-d H:i:s', $v['user']['overdue_time'])) : '';
            }
        }
        $count = $this->dao->count($where);
        return compact('list', 'count');
    }

	/**
	 * 门店付费会员统计详情列表
	 * @param int $store_id
	 * @param int $staff_id
	 * @param array $time
	 * @param string $timeType
	 * @return array|array[]
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
    public function time(int $store_id, int $staff_id, array $time = [], string $timeType = 'day')
    {
        if (!$time) {
            return [[], []];
        }
        $where = ['store_id' => $store_id, 'paid' => 1, 'type' => [0, 1, 2, 4]];
        if ($staff_id) {
            $where['staff_id'] = $staff_id;
        }
		return $this->dao->otherOrderAddTimeList($where, $time, $timeType);
    }

}
